//
//  HomeFirstSectionHeaderView.m
//  UI高级项目
//
//  Created by TonyStart on 16/9/1.
//  Copyright © 2016年 com.wx. All rights reserved.
//

#import "HeaderScrollerView.h"
#import "SCNetworkTool.h"
#import "SCAlertView.h"

@interface HeaderScrollerView()<UIScrollViewDelegate>
{
    dispatch_source_t _source_timer;//定时器
    NSInteger _currentPage;//记录当前page
}
@property(nonatomic,strong)UIScrollView *scrollView;

@property(nonatomic,strong)UIPageControl *pageControl;

@end
@implementation HeaderScrollerView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self =[super initWithFrame:frame]) {
        [self setupScroller];
    }
    return self;
}

-(void)setupScroller{
    _currentPage = 0;
    
    [self addSubview:self.scrollView];
    [self requestImageArray];
    self.backgroundColor = [UIColor redColor];
    
}
-(void)setupScrollerView{
    _scrollView.contentSize = CGSizeMake(self.bounds.size.width*self.scrollImgArray.count, self.bounds.size.height);
    for (int i=0; i<_scrollImgArray.count; i++) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(i*self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height)];
        UIImage * image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:_scrollImgArray[i]];
        if (image) {
            imgView.image = image;
//            NSLog(@"从缓存获取图片%@",_scrollImgArray[i]);
        }else{
            [imgView sd_setImageWithURL:_scrollImgArray[i] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//                NSLog(@"图片下载完成%@",imageURL);
            }];
        }
        [_scrollView addSubview:imgView];
        
    }
    
    [self addSubview:self.pageControl];
    [self beginAutoScroll];
}

-(UIScrollView *)scrollView{
    if (!_scrollView) {
        
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        
        _scrollView.bounces = NO;
        
        
        _scrollView.pagingEnabled = YES;
        
        
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
        
    }
    return _scrollView;
}
//GCD定时器
-(void)beginAutoScroll{
    //创建定时器
    _source_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    
    dispatch_source_set_timer(_source_timer, dispatch_walltime(NULL, NSEC_PER_SEC * 3.0), 3.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    //在这里执行事件
    dispatch_source_set_event_handler(_source_timer, ^{
        
        [self imgAutoScroll];
    });
    
    dispatch_resume(_source_timer);
    
    
}
//
-(void)imgAutoScroll{
    if (_currentPage<self.scrollImgArray.count-1) {
        _currentPage++;
    }else{
        _currentPage = 0;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.pageControl.currentPage = _currentPage;
        self.scrollView.contentOffset = CGPointMake(_currentPage*self.bounds.size.width, 0);
    });
    
    
}
//pageController
-(UIPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20)];
        _pageControl.backgroundColor = [UIColor grayColor];
        _pageControl.layer.opacity = 0.5;
        _pageControl.currentPage = _currentPage;
        _pageControl.numberOfPages = _scrollImgArray.count;
        _pageControl.center = CGPointMake(self.center.x, self.bounds.size.height-10);
        _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        
    }
    return _pageControl;
}

-(void)requestImageArray{
    NSString *url = urlAndParamBuild(@"Appapi", @"slide", @"index");
    _scrollImgArray = [NSArray array];
    NSMutableArray *tempImgArray = [NSMutableArray array];
    [[SCNetworkTool shared] requestDataWithMethod:GET url:url finish:^(id data, NSError *err,NSInteger code) {
        if (err) {
            [SCAlertView alertViewWithTitle:@"网络请求出错啦!"];
            return;
        }
     
        for (NSDictionary *dict in data) {
            [tempImgArray addObject:[NSString stringWithFormat:@"http://www.scxxhs.com%@",dict[@"slide_pic"]]];
            
        }
    
        _scrollImgArray = tempImgArray;
        [self setupScrollerView];
    }];

}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //开始拖拽的时候让定时器暂停
    [self pauseTimer];
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //结束拖拽的时候让定时器开始
    [self resumeTimer];
}
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    //通过停止拖拽后 scrollerView最终停留的contentOfset来确定当前是在第几页
    CGPoint currentPoint =*targetContentOffset;
    _currentPage =  currentPoint.x /self.bounds.size.width;
    self.pageControl.currentPage = _currentPage;
}
//暂停
-(void)pauseTimer{
    if (_source_timer) {
        dispatch_suspend(_source_timer);
    }
}
//开始
-(void)resumeTimer{
    if (_source_timer) {
        //3秒后重新开启定时器
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_resume(_source_timer);
        });
        
        
        
    }
}
//停止
-(void)stopTimer{
    if (_source_timer) {
        dispatch_source_cancel(_source_timer);
    }
}
@end
